import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, message, Modal, Dropdown, Typography, Badge, Progress } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, SendOutlined, EyeOutlined, BellOutlined } from '@ant-design/icons';
import { getNotificationList, deleteNotification, sendNotification, getNotificationSendStatus } from '@/services/systemManagementApi';
import NotificationForm from './components/NotificationForm';
import NotificationPreview from './components/NotificationPreview';
import SendStatusModal from './components/SendStatusModal';
import moment from 'moment';

const { Text } = Typography;

const NotificationList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [notificationFormVisible, setNotificationFormVisible] = useState(false);
  const [notificationPreviewVisible, setNotificationPreviewVisible] = useState(false);
  const [sendStatusVisible, setSendStatusVisible] = useState(false);
  const [currentNotification, setCurrentNotification] = useState<SYSTEM.NotificationModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 通知类型标签颜色映射
  const typeColorMap = {
    system: 'blue',
    announcement: 'green',
    maintenance: 'orange',
    promotion: 'purple',
  };

  // 状态标签颜色映射
  const statusColorMap = {
    draft: 'orange',
    sent: 'green',
    scheduled: 'blue',
  };

  // 目标类型标签颜色映射
  const targetTypeColorMap = {
    all: 'cyan',
    role: 'geekblue',
    user: 'magenta',
  };

  // 表格列定义
  const columns: ProColumns<SYSTEM.NotificationModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '通知标题',
      dataIndex: 'title',
      width: 200,
      ellipsis: true,
      copyable: true,
      render: (text) => (
        <Text style={{ maxWidth: 180 }} ellipsis={{ tooltip: text }}>
          {text}
        </Text>
      ),
    },
    {
      title: '通知内容',
      dataIndex: 'content',
      width: 250,
      search: false,
      ellipsis: true,
      render: (content) => (
        <Text type="secondary" style={{ maxWidth: 230 }} ellipsis={{ tooltip: content }}>
          {content}
        </Text>
      ),
    },
    {
      title: '通知类型',
      dataIndex: 'type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        system: { text: '系统通知', status: 'Processing' },
        announcement: { text: '公告通知', status: 'Success' },
        maintenance: { text: '维护通知', status: 'Warning' },
        promotion: { text: '推广通知', status: 'Error' },
      },
      render: (_, record) => {
        const typeMap = {
          system: '系统通知',
          announcement: '公告通知',
          maintenance: '维护通知',
          promotion: '推广通知',
        };
        return (
          <Tag color={typeColorMap[record.type]}>
            {typeMap[record.type]}
          </Tag>
        );
      },
    },
    {
      title: '目标用户',
      dataIndex: 'target_type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        all: { text: '全部用户', status: 'Default' },
        role: { text: '指定角色', status: 'Processing' },
        user: { text: '指定用户', status: 'Warning' },
      },
      render: (_, record) => {
        const targetMap = {
          all: '全部用户',
          role: '指定角色',
          user: '指定用户',
        };
        return (
          <Tag color={targetTypeColorMap[record.target_type]}>
            {targetMap[record.target_type]}
          </Tag>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        draft: { text: '草稿', status: 'Warning' },
        sent: { text: '已发送', status: 'Success' },
        scheduled: { text: '已排期', status: 'Processing' },
      },
      render: (_, record) => {
        const statusMap = { draft: '草稿', sent: '已发送', scheduled: '已排期' };
        return (
          <Tag color={statusColorMap[record.status]}>
            {statusMap[record.status]}
          </Tag>
        );
      },
    },
    {
      title: '发送进度',
      dataIndex: 'read_count',
      width: 120,
      search: false,
      render: (_, record) => {
        if (record.status === 'draft') return '-';
        const percentage = record.total_recipients > 0 
          ? Math.round((record.read_count / record.total_recipients) * 100) 
          : 0;
        return (
          <div>
            <Progress 
              percent={percentage} 
              size="small" 
              status={percentage > 80 ? 'success' : 'normal'}
            />
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {record.read_count}/{record.total_recipients}
            </Text>
          </div>
        );
      },
    },
    {
      title: '排期时间',
      dataIndex: 'scheduled_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
      render: (time) => time ? moment(time).format('MM-DD HH:mm') : '-',
    },
    {
      title: '发送时间',
      dataIndex: 'sent_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
      render: (time) => time ? moment(time).format('MM-DD HH:mm') : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="preview"
          type="link"
          size="small"
          onClick={() => handlePreview(record)}
        >
          预览
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
                disabled: record.status === 'sent',
              },
              {
                key: 'send',
                label: '发送',
                icon: <SendOutlined />,
                onClick: () => handleSend(record),
                disabled: record.status === 'sent',
              },
              {
                key: 'status',
                label: '发送状态',
                icon: <EyeOutlined />,
                onClick: () => handleViewSendStatus(record),
                disabled: record.status === 'draft',
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理预览
  const handlePreview = (record: SYSTEM.NotificationModel) => {
    setCurrentNotification(record);
    setNotificationPreviewVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: SYSTEM.NotificationModel) => {
    setCurrentNotification(record);
    setEditMode('edit');
    setNotificationFormVisible(true);
  };

  // 处理发送
  const handleSend = (record: SYSTEM.NotificationModel) => {
    Modal.confirm({
      title: '确认发送',
      content: `确定要发送通知 "${record.title}" 吗？发送后将无法修改。`,
      okText: '确认发送',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await sendNotification(record.id);
          message.success(`通知发送成功，共发送给 ${response.data.sent_count} 个用户`);
          actionRef.current?.reload();
        } catch (error) {
          message.error('通知发送失败');
        }
      },
    });
  };

  // 处理查看发送状态
  const handleViewSendStatus = (record: SYSTEM.NotificationModel) => {
    setCurrentNotification(record);
    setSendStatusVisible(true);
  };

  // 处理删除
  const handleDelete = (record: SYSTEM.NotificationModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除通知 "${record.title}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteNotification(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentNotification(undefined);
    setEditMode('create');
    setNotificationFormVisible(true);
  };

  return (
    <PageContainer>
      <ProTable<SYSTEM.NotificationModel>
        headerTitle="通知管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建通知
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getNotificationList({
            page: params.current,
            limit: params.pageSize,
            keyword: params.title,
            type: params.type,
            target_type: params.target_type,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1600 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 通知表单弹窗 */}
      <NotificationForm
        visible={notificationFormVisible}
        mode={editMode}
        initialValues={currentNotification}
        onCancel={() => setNotificationFormVisible(false)}
        onSuccess={() => {
          setNotificationFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 通知预览弹窗 */}
      <NotificationPreview
        visible={notificationPreviewVisible}
        notification={currentNotification}
        onCancel={() => setNotificationPreviewVisible(false)}
      />

      {/* 发送状态弹窗 */}
      <SendStatusModal
        visible={sendStatusVisible}
        notification={currentNotification}
        onCancel={() => setSendStatusVisible(false)}
      />
    </PageContainer>
  );
};

export default NotificationList;
